import React from 'react';
import { Input, Button, Table, Pagination, Modal } from 'antd';
import statuscode from '../../statuscode/index';
import axios from 'axios';
import Tips from '../../Tips/index';
import JoinNetWork from './Join';
import Detail from './detail';
import Invite from './invite';
import { connect } from 'react-redux';
import './index.less';
import Bread from '../../common/Bread/index';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
var networkstatus = {
  1000: '创建中',
  1010: '创建成功',
  1020: '创建失败',
  2000: '启动中',
  2010: '启动成功',
  2020: '启动失败',
  3000: '停止中',
  3010: '已停止',
  2030: '启动失败',
  3020: '停止失败',
  20: '审批中',
  30: '加入中',
  40: '加入中',
  51: '加入失败',
  41: '加入失败',
  52: '加入失败',
};
class NetSandBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: '',
      data: [],
      page: 1,
      limit: 10,
      totalnum: 0,
      message: '',
      update: false,
      visible: false,
      joinnetworkvisible: false,
      textdatanet: ''
    };
  }
  componentWillMount() {
    this.ismounted = true;
    this.getData(this.state.page, this.state.limit);
  }
  componentWillUnmount() {
    this.ismounted = false;
  }
  componentWillUpdate(nextprops) {
    if (nextprops.changeOrgid != this.props.changeOrgid) {
      this.getData(this.state.page, this.state.limit, nextprops.changeOrgid);
    }
  }
  columns = [{
    title: '名称',
    dataIndex: '名称',
    key: '名称',
  }, {
    title: 'Peer节点数',
    dataIndex: 'Peer节点数',
    key: 'Peer节点数',
  }, {
    title: 'Orderer节点数',
    dataIndex: 'Orderer节点数',
    key: 'Orderer节点数',
  }, {
    title: '备注',
    dataIndex: '备注',
    key: '备注',
  }, {
    title: '状态',
    dataIndex: '状态',
  }, {
    title: '控制网络',
    key: '控制网络',
    render: (text, record) => (
      <span className="controlnet">
        {/* <span unselectable="on" className="startnet netdisable " size="small" >启动</span>
        <span unselectable="on" className="stopnet netdisable" size="small" >停止</span> */}
        <span className="joinnet" size="small" onClick={this.joinnetvisble.bind(this, text, record)} style={{ display: record.permission == 0 ? 'none' : '' }}>加入该网络</span>
      </span>
    ),
  }, {
    title: '其他操作',
    key: '其他操作',
    render: (text, record) => (
      <span className="controlnet">
        <span className="datailnet" size="small" onClick={this.detailshowModal.bind(this, text, record)} > 详情</span >
        {/* <span className="invitenet" size="small" onClick={this.inviteshowModal.bind(this, text, record)} >邀请组织</span> */}
        {/* <span unselectable="on" className="invitenet netdisable" size="small" >审批记录</span> */}
      </span>
    ),
  }];
  stateData = {
    page: ['10', '20', '30', '40', '50', '60', '70', '80', '90']
  }
  handleCancel = () => {
    this.setState({
      visiblejoinnet: false
    });
  }
  handleChancel = () => {
    this.setState({
      visible: false,
    });
  }
  joinnetvisble = (text, i) => {
    this.setState({
      visiblejoinnet: true,
      textdatanet: text
    });
  }

  joinnetworkshowModal = () => {
    this.setState({
      joinnetworkvisible: true,
    });
  }
  joinnetworkhandleChancel = () => {
    this.setState({
      joinnetworkvisible: false,
    });
  }
  joinnetworkhandleCreate = (_this) => {
  }
  detailshowModal = (text) => {
    const _this = this;
    this.setState({
      message: 'loading'
    });
    var Token = localStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/sandbox/fabric/queryBaasNetwork',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { networkName: text.networkname }
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState({
            detailvisible: true,
            title: text['名称'],
            detaildata: response.data.data,
            message: message
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      })
      .catch(function (error) {
        console.log(error);
        if (_this.ismounted) {
          _this.setState({
            message: '请求失败，请刷新重试'
          }, () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          });
        }
      });
  }
  detailhandleChancel = () => {
    this.setState({
      detailvisible: false,
    });
  }

  inviteshowModal = (text) => {
    const Token = localStorage.getItem('token');
    this.setState({
      message: 'loading'
    });
    const _this = this;
    var networkName = text.networkname ? text.networkname : text.networkName;
    axios({
      method: 'get',
      url: '/api/sandbox/fabric/queryBaasNetworkByAdmin',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { networkName: networkName }
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          if (code == 200) {
            _this.setState({
              invitevisible: true,
              detailvisible: false,
              title: text.networkname,
              invitationdata: response.data.data,
              message: ''
            }, () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            });
          } else {
            _this.setState({
              message: message
            }, () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            });
          }
        }
      })
      .catch(function (error) {
      });
  }


  invitehandleChancel = () => {
    this.setState({
      invitevisible: false,
    });
  }
  onShowSizeChange=(current, pageSize) => {
    this.getData(current, pageSize);
    this.setState({
      limit: pageSize
    });
  }
  onChange=(pageNumber) => {
    this.getData(pageNumber);
  }
  changesearch = (ev) => {
    this.setState({ searchvalue: ev.target.value });
  }
  search = () => {
    this.getData(this.state.page, this.state.limit, this.props.changeOrgid, this.state.searchvalue);
  }
  tips = (str) => {
    this.setState({
      message: str
    });
    setTimeout(() => {
      this.setState({
        message: ''
      });
    }, 1000);
  }

  join = () => {
    var text = this.state.textdatanet;
    const _this = this;
    var networkName = text.networkname;
    var data = {
      FabricFlag: networkName, OrgId: this.props.changeOrgid, 'RequestType': 'RegisterUserReq', 'ChannelId': 'mychannel',
    };
    this.setState({
      message: 'loading'
    });
    var Token = localStorage.getItem('token');
    axios.post('/api/sandbox/fabric/registerUser', data, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token,
      }
    })
      .then(function (response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          if (code == 200) message = '加入成功！';
          _this.setState({
            message: message
          });
          setTimeout(() => {
            if (code == 200) {
              _this.props.dispatch({
                type: 'updatenet',
                onoff: true
              });
              setTimeout(() => {
                _this.getData(_this.state.page, _this.state.limit);
              });
            }
            _this.setState({
              message: '',
              visiblejoinnet: false
            });
          }, 1000);
        }
      })
      .catch(function (error) {
      });
  }

  getData = (page, limit = this.state.limit, changeOrgid = this.props.changeOrgid, searchdata) => {
    if (!changeOrgid) return;
    const $this = this;
    this.setState({
      message: 'loading'
    });
    const Token = localStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/sandbox/fabric/queryNetWorkList',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { 'page': page, limit: limit, orgId: changeOrgid, nickname: searchdata }
    })
      .then(function (response) {
        if ($this.ismounted) {
          let data = [];
          var code = response.data.code;
          // if (statuscode[response.data.code] == undefined) code = '500'
          var message = statuscode[code];
          response.data && response.data.data && response.data.data.rows && response.data.data.rows.forEach((e, i) => {
            data.push({
              key: String(i),
              '名称': e.nickname,
              'Peer节点数': e.peerNum,
              'Orderer节点数': e.ordererNum,
              '备注': e.remark,
              '状态': networkstatus[e.networkStatus],
              networkname: e.networkName,
              permission: e.permission
            });
          });
          $this.setState({
            data: data,
            totalnum: response.data && response.data.data && response.data.data.total ? response.data.data.total : 0,
            message: message
          }, () => {
            setTimeout(() => {
              $this.setState({
                message: '',
              });
            }, 1000);
          });
        }
      })
      .catch(function (error) {
      });
  }

  render() {
    // var joinnet = '';
    // if (true) {
    //   joinnet = (
    //     <div className="index-buttons">
    //       <Button type="primary" onClick={this.joinnetworkshowModal}>加入一个网络</Button>
    //     </div>
    //   )
    // }
    return (
      <div>
        <Bread bread={['网络管理', ['网络管理', 'net']]} />
        {/* <div className="index-buttons"> */}
        {/* <Button type="primary" disabled>创建一个网络</Button> */}
        {/* <Button type="Default" style={{ marginLeft: 10 }} onClick={this.joinnetworkshowModal}>加入一个网络</Button> */}
        {/* </div> */}
        {/* {joinnet} */}
        <div className="inviteUserBox">
          <Input placeholder="请输入网络名称" className="input" onChange={this.changesearch} />
          <Button type="primary" className="search" onClick={this.search}><img src={require('../../../static/img/search_icon.png')} /></Button>
        </div>
        <Table className="netTable" columns={this.columns} dataSource={this.state.data} bordered Paginatio={this.onShowSizeChange} pagination={false} />
        <div className="page_foot">
          <span className="data_num">共{this.state.totalnum}条</span>
          <Pagination pageSizeOptions={this.stateData.page} className="page" showSizeChanger showQuickJumper onShowSizeChange={this.onShowSizeChange} defaultCurrent={1} total={this.state.totalnum} onChange={this.onChange} />
        </div>
        <JoinNetWork
          visible={this.state.joinnetworkvisible}
          onCancel={this.joinnetworkhandleChancel}
          onCreate={this.joinnetworkhandleCreate}
        />
        <Detail
          visible={this.state.detailvisible}
          stop={this.stop}
          onCancel={this.detailhandleChancel}
          title={this.state.title}
          // onCreate={this.detailhandleCreate}
          inviteshowModal={this.inviteshowModal}
          start={this.start}
          detaildata={this.state.detaildata}
        />
        <Invite
          visible={this.state.invitevisible}
          onCancel={this.invitehandleChancel}
          title={this.state.title}
          invitationdata={this.state.invitationdata}
        />
        <Modal style={{ 'zIndex': 1000 }}
          visible={this.state.visiblejoinnet}
          title="提示"
          closable={false}
          iconType="warning"
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>取消</Button>,
            <Button key="submit" type="primary" onClick={this.join}>
              确定
            </Button>,
          ]}
        >
          <p className="textAlign">
            <span className="CommonTips">您是否确认加入网络：{this.state.textdatanet['名称'] ? this.state.textdatanet['名称'] : this.state.textdatanet}</span>
            {/* <span className="userName"> {this.state.textdata ? this.state.textdata['组织名称'] : ''} 的申请</span> */}
          </p>
        </Modal>
        <Tips message={this.state.message} />
      </div>
    );
  }
}

export default connect((state) => {
  return { ...state };
})(NetSandBox);
